package com.dev.module_zqc_sleep.mvi.ui

import android.app.Activity
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.ArrowBackIosNew
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableIntState
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.dev.module_ui_composable.coil.LoadAsyncImage
import com.dev.module_ui_composable.components.CustomTabLayout
import com.dev.module_ui_composable.view.ad.BannerAdView
import com.dev.module_zqc_sleep.mvi.vm.AssetsViewModel
import com.fwlst.lib_base.utils.AdUtils


@Stable
private val classifyTabs = listOf("助眠", "治愈", "静心", "白噪音", "自然音", "助眠脑波", "冥想")

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun ClassifyScreen(
    assetsViewModel: AssetsViewModel = viewModel(),
    position: Int,
    onBackClick: () -> Unit,
    onPlayAudio: (audioPath: String, tabName: String) -> Unit
) {
    val context = LocalContext.current
    val selectedTabIndex = remember { mutableIntStateOf(position) }
    val pagerState = rememberPagerState { 0 }

    val assetImages by assetsViewModel.assetImages.collectAsStateWithLifecycle()
    val assetAudiosSplit by assetsViewModel.assetAudiosSplit.collectAsStateWithLifecycle()
    val classify by assetsViewModel.classify.collectAsStateWithLifecycle()

    val whiteNoisesForCurrentTab = assetAudiosSplit.getOrNull(selectedTabIndex.intValue) ?: emptyList()
    val currentClassify = classify.find { it.name == classifyTabs[selectedTabIndex.intValue] }
    val currentClassifyItems = currentClassify?.classify ?: emptyList()

    LaunchedEffect(selectedTabIndex.intValue) {
        assetsViewModel.loadAssetImages(context, selectedTabIndex.intValue)
    }
    LaunchedEffect(Unit) {
        assetsViewModel.loadWhiteNoiseAndClassifyJson(context)
    }

    Scaffold(
        modifier = Modifier.fillMaxSize(),
        topBar = {
            Column(modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
                TopTabContent(
                    modifier = Modifier.statusBarsPadding(),
                    selectedTabIndex = selectedTabIndex,
                    pagerState = pagerState,
                    onBackClick = { onBackClick() }
                )

                BannerAdView()
            }
        },
        containerColor = Color.White
    ) { innerPadding ->
        LazyVerticalGrid(
            columns = GridCells.Fixed(2),
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding),
            contentPadding = PaddingValues(20.dp),
            horizontalArrangement = Arrangement.spacedBy(15.dp),
            verticalArrangement = Arrangement.spacedBy(20.dp)
        ) {
            itemsIndexed(
                items = assetImages,
                contentType = { _, item -> item }
            ) { index, imagePath ->
                Surface(
                    onClick = {
                        AdUtils.checkFunction(context as Activity) {
                            onPlayAudio(
                                whiteNoisesForCurrentTab[index].ossId,
                                classifyTabs[selectedTabIndex.intValue]
                            )
                        }
                    },
                    modifier = Modifier.size(160.dp)
                ) {
                    Box(modifier = Modifier.fillMaxSize()) {
                        LoadAsyncImage(
                            data = "file:///android_asset/$imagePath",
                            modifier = Modifier.matchParentSize(),
                            contentScale = ContentScale.FillBounds
                        )

                        Column(
                            modifier = Modifier
                                .padding(8.dp)
                                .align(Alignment.TopEnd),
                            verticalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            currentClassifyItems.take(2).forEach { item ->
                                Surface(
                                    shape = RoundedCornerShape(12.dp),
                                    color = MaterialTheme.colorScheme.onBackground.copy(0.5f)
                                ) {
                                    Text(
                                        text = item,
                                        modifier = Modifier.padding(3.dp),
                                        color = Color.White,
                                        fontSize = 10.sp
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun TopTabContent(
    modifier: Modifier = Modifier,
    tabs: List<String> = classifyTabs,
    selectedTabIndex: MutableIntState,
    pagerState: PagerState,
    onBackClick: () -> Unit
) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .height(65.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceEvenly
    ) {
        IconButton(onClick = onBackClick) {
            Icon(
                imageVector = Icons.Rounded.ArrowBackIosNew,
                contentDescription = null
            )
        }

        CustomTabLayout(
            tabs = tabs,
            pagerState = pagerState,
            selectedTabIndex = selectedTabIndex
        )
    }
}